package chen.yi.web.config;

import chen.yi.component.operate.log.annotate.Username;
import cn.hutool.http.server.HttpServerRequest;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * 跨域配置
 * @author huat
 **/
@Configuration
public class CorsConfig {
    @Value("${chen-yi.cross.white.url:*}")
    private String whiteUrl;
    @Bean
    public FilterRegistrationBean corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        String[] split = whiteUrl.split(",");
        for (String str:split){
            corsConfiguration.addAllowedOrigin(str); // 1允许任何域名使用
        }
        corsConfiguration.addAllowedHeader("*"); // 2允许任何头
        corsConfiguration.addAllowedMethod("*"); // 3允许任何方法（post、get等）
        source.registerCorsConfiguration("/**", corsConfiguration);
        //如果没有下面两行则会出现无权限访问时会出现跨域错误
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new CorsFilter(source));
        // 代表这个过滤器在众多过滤器中级别最高，也就是过滤的时候最先执行
        filterRegistrationBean.setOrder(Ordered.HIGHEST_PRECEDENCE);
        return filterRegistrationBean;
    }

    @Username
    public String getUsername(HttpServletRequest request){
        return "";
    }
}
